import { memo, useEffect, useState } from 'react'
import { Typography } from 'antd'
import { api_getStateData } from '@/api'
import { useRequest } from 'ahooks'
import { useParams } from 'react-router-dom'
import { getComponentConfByType } from '@/components/QuestionComponents'

const { Title } = Typography

type PropsType = {
  selectedComponentId: string
  selectedComponentType: string
}

const ChartState = memo((props: PropsType) => {
  const { selectedComponentId, selectedComponentType } = props
  const { id = '' } = useParams()

  const [stat, setStat] = useState([])
  const { run } = useRequest(
    async (id, selectedComponentId) => await api_getStateData(id, selectedComponentId),
    {
      manual: true,
      onSuccess: res => {
        setStat(res.state)
      },
    }
  )

  useEffect(() => {
    if (selectedComponentId) {
      run(id, selectedComponentId)
    }
  }, [id, selectedComponentId])

  const StatElem = () => {
    if (!selectedComponentId) return <div>未选中任何组件</div>
    const { statComponent: StatComponent } = getComponentConfByType(selectedComponentType) || {}
    if (!StatComponent) return <div>该组件暂无统计图表</div>
    return <StatComponent stat={stat} />
  }

  return (
    <>
      <Title level={3}>图表统计</Title>
      <StatElem />
    </>
  )
})

export default ChartState
